package domain

import (
	"context"
	"errors"
	"gitee.com/tietang/terrace-go/v2/example/order"
	"github.com/segmentio/ksuid"
)

type OrderDomain struct {
	order.Order
	Repo OrderRepository
	ext  order.CreateOrderDomainExt
}

func NewOrderDomain() OrderDomain {
	do := OrderDomain{
		ext: order.GetCreateOrderDomainExtProxy(),
	}
	return do
}

func (o *OrderDomain) PluginCode() string {
	return "order"
}

//创建logNo 的逻辑
func (d *OrderDomain) createTradeNo() {
	//暂时采用ksuid的ID生成策略来创建No
	//后期会优化成可读性比较好的，分布式ID
	//全局唯一的ID
	d.TradeNo = ksuid.New().Next().String()
}

func (o *OrderDomain) Create() (id int64, err error) {
	ctx := context.Background()
	if err = o.ext.OnValidate(ctx, &o.Order); err != nil {
		return -1, err
	}
	o.createTradeNo()
	if err = o.ext.PreSave(ctx, &o.Order); err != nil {
		return -1, err
	}
	id, err = o.Repo.Save(o.Order)
	if err != nil {
		return id, err
	}
	if id <= 0 {
		return -1, errors.New("创建失败")
	}
	return id, err
}

func (o *OrderDomain) ChangeStatus() bool {
	row, err := o.Repo.UpdateStatus(o.Order)
	if row <= 0 || err != nil {
		return false
	}
	return true
}

func (o *OrderDomain) GetByTradeNo() *order.Order {
	q := o.Repo.GetOne(o.TradeNo)
	return q
}

func (o *OrderDomain) Get() *order.Order {
	q := o.Repo.Get(o.Id)
	return q
}
